﻿using System;
using System.Configuration;
using System.Web.Configuration;

namespace Netkk.Data.Provider
{
    public class DataProviderManager
    {
        private static DataProvider defaultProvider;
        private static DataProviderCollection providers;
        private static object locker = new object();

        static DataProviderManager()
        {
            Initialize();
        }

        private static void Initialize()
        {
            // Avoid claiming lock if providers are already loaded
            if (defaultProvider == null)
            {
                lock (locker)
                {
                    // Do this again to make sure _provider is still null
                    if (defaultProvider == null)
                    {
                        DataProviderConfiguration configuration = (DataProviderConfiguration)WebConfigurationManager.GetSection("netkk.data/dataProvider");

                        if (configuration == null)
                        {
                            throw new ConfigurationErrorsException("DataProvider configuration section is not set correctly.");
                        }

                        providers = new DataProviderCollection();

                        ProvidersHelper.InstantiateProviders(configuration.Providers, providers, typeof(DataProvider));

                        providers.SetReadOnly();

                        defaultProvider = providers[configuration.Default];

                        if (defaultProvider == null)
                        {
                            throw new Exception("defaultProvider");
                        }
                    }
                }

            }
        }

        public static DataProvider Provider
        {
            get { return defaultProvider; }
        }

        public static DataProviderCollection Providers
        {
            get { return providers; }
        }
    }

}
